﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Configuration;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// ConfigSetter.xaml 的交互逻辑
    /// </summary>
    public partial class ConfigSetter : Window
    {
        public ConfigSetter()
        {
            InitializeComponent();
        }
        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        private void DockPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Hidden;
        }
        //string LocalIP = ConfigurationManager.AppSettings["LocalIP"];
        string CompetitionDbConnStr = ConfigurationManager.AppSettings["CompetitionDbConnStr"];
        string OperLogDbConnStr = ConfigurationManager.AppSettings["OperLogDbConnStr"];
        string ScoreService = AppConfigSave.GetEndpointAddress("ScoreService");
        string DriverClientService = AppConfigSave.GetEndpointAddress("DriverClientService");
        string DriverManageService = AppConfigSave.GetEndpointAddress("DriverManageService");
        string AccountManageService = AppConfigSave.GetEndpointAddress("AccountManageService");
        string DatabaseService = AppConfigSave.GetEndpointAddress("DatabaseService");
        string DispatcherManageService = AppConfigSave.GetEndpointAddress("DispatcherManageService");
        string DispatcherClientService = AppConfigSave.GetEndpointAddress("DispatcherClientService");
        //获取要自动运行的应用程序名
        string strName = AppDomain.CurrentDomain.BaseDirectory + "ET.ScoreTeacherClient.exe";
        bool isLoaded = false;
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //本地
            //string[] Local = LocalIP.Split('.');
            //if (Local.Length > 3)
            //{
            //    Localtbx1.Text = Local[0];
            //    Localtbx2.Text = Local[1];
            //    Localtbx3.Text = Local[2];
            //    Localtbx4.Text = Local[3];
            //}
            //数据库
            string[] DbConn = CompetitionDbConnStr.Split(new char[3] { '=', '.', ';' });
            if (DbConn.Length > 6)
            {
                DbConntbx1.Text = DbConn[1];
                DbConntbx2.Text = DbConn[2];
                DbConntbx3.Text = DbConn[3];
                DbConntbx4.Text = DbConn[4];
                DbConnNametbx.Text = DbConn[6];
                DbConnIdtbx.Text = DbConn[8];
                DbConnpswtbx.Text = DbConn[10];
            }
            //string[] Service = HeartBeatService.Split(new char[3] { '/', '.', ':' });
            //if (Service.Length > 6)
            //{
            //    Servicetbx1.Text = Service[3];
            //    Servicetbx2.Text = Service[4];
            //    Servicetbx3.Text = Service[5];
            //    Servicetbx4.Text = Service[6];
            //    ServicePorttbx.Text = Service[7];
            //}
            //日志数据库
            string[] DblogConn = OperLogDbConnStr.Split(new char[3] { '=', '.', ';' });
            if (DblogConn.Length > 6)
            {
                DblogConntbx1.Text = DblogConn[1];
                DblogConntbx2.Text = DblogConn[2];
                DblogConntbx3.Text = DblogConn[3];
                DblogConntbx4.Text = DblogConn[4];
                DblogConnNametbx.Text = DblogConn[6];
                DblogConnIdtbx.Text = DblogConn[8];
                DblogConnpswtbx.Text = DblogConn[10];
            }
            //考核分析服务
            string[] ScoreService = this.ScoreService.Split(new char[3] { '/', '.', ':' });
            if (ScoreService.Length > 7)
            {
                ScoreServicetbx1.Text = ScoreService[3];
                ScoreServicetbx2.Text = ScoreService[4];
                ScoreServicetbx3.Text = ScoreService[5];
                ScoreServicetbx4.Text = ScoreService[6];
                ScoreServicePorttbx.Text = ScoreService[7];
            }
            //驾驶服务
            string[] DriverClient = DriverClientService.Split(new char[3] { '/', '.', ':' });
            if (DriverClient.Length > 7)
            {
                DriverClienttbx1.Text = DriverClient[3];
                DriverClienttbx2.Text = DriverClient[4];
                DriverClienttbx3.Text = DriverClient[5];
                DriverClienttbx4.Text = DriverClient[6];
                DriverClientPorttbx.Text = DriverClient[7];
            }
            //驾驶服务教员端
            string[] DriverManage = DriverManageService.Split(new char[3] { '/', '.', ':' });
            if (DriverManage.Length > 7)
            {
                DriverManagetbx1.Text = DriverManage[3];
                DriverManagetbx2.Text = DriverManage[4];
                DriverManagetbx3.Text = DriverManage[5];
                DriverManagetbx4.Text = DriverManage[6];
                DriverManagePorttbx.Text = DriverManage[7];
            }
            //账户管理服务教员端
            string[] AccountManage = AccountManageService.Split(new char[3] { '/', '.', ':' });
            if (AccountManage.Length > 7)
            {
                AccountManagetbx1.Text = AccountManage[3];
                AccountManagetbx2.Text = AccountManage[4];
                AccountManagetbx3.Text = AccountManage[5];
                AccountManagetbx4.Text = AccountManage[6];
                AccountManagePorttbx.Text = AccountManage[7];
            }
            //数据库操作服务教员端
            string[] Database = DatabaseService.Split(new char[3] { '/', '.', ':' });
            if (Database.Length > 7)
            {
                Databasetbx1.Text = Database[3];
                Databasetbx2.Text = Database[4];
                Databasetbx3.Text = Database[5];
                Databasetbx4.Text = Database[6];
                DatabasePorttbx.Text = Database[7];
            }
            //调度考核服务教员端应用
            string[] DispatcherManage = DispatcherManageService.Split(new char[3] { '/', '.', ':' });
            if (DispatcherManage.Length > 7)
            {
                DispatcherManagetbx1.Text = DispatcherManage[3];
                DispatcherManagetbx2.Text = DispatcherManage[4];
                DispatcherManagetbx3.Text = DispatcherManage[5];
                DispatcherManagetbx4.Text = DispatcherManage[6];
                DispatcherManagePorttbx.Text = DispatcherManage[7];
            }
            //心跳服务
            string[] DispatcherClient = DispatcherClientService.Split(new char[3] { '/', '.', ':' });
            if (DispatcherClient.Length > 7)
            {
                DispatcherClienttbx1.Text = DispatcherClient[3];
                DispatcherClienttbx2.Text = DispatcherClient[4];
                DispatcherClienttbx3.Text = DispatcherClient[5];
                DispatcherClienttbx4.Text = DispatcherClient[6];
                DispatcherClientPorttbx.Text = DispatcherClient[7];
            }
            isLoaded = true;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBut_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定保存设置吗？保存后程序将重新启动。", "", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                //保存数据库
                string DbConnStr = "Server=" + DbConntbx1.Text.Trim() + "." + DbConntbx2.Text.Trim() + "."
                    + DbConntbx3.Text.Trim() + "." + DbConntbx4.Text.Trim() + ";Database=" + DbConnNametbx.Text.Trim() + "; User id=" + DbConnIdtbx.Text.Trim() + ";pwd="+ DbConnpswtbx.Text + ";";
                AppConfigSave.UpDataToAppKey("CompetitionDbConnStr", DbConnStr);
                //保存本地
                //string LocalStr = Localtbx1.Text.Trim() + "." + Localtbx2.Text.Trim() + "."
                //   + Localtbx3.Text.Trim() + "." + Localtbx4.Text.Trim();
                //AppConfigSave.UpDataToAppKey("LocalIP", LocalStr);
                //保存日志数据库
                string DblogConnStr = "Server=" + DblogConntbx1.Text.Trim() + "." + DblogConntbx2.Text.Trim() + "."
                   + DblogConntbx3.Text.Trim() + "." + DblogConntbx4.Text.Trim() + ";Database=" + DblogConnNametbx.Text.Trim() + "; User id=" + DblogConnIdtbx.Text.Trim() + ";pwd=" + DblogConnpswtbx.Text + ";";
                AppConfigSave.UpDataToAppKey("CompetitionDbConnStr", DbConnStr);
                //保存服务
                string ScoreService = "http://" + ScoreServicetbx1.Text.Trim() + "." + ScoreServicetbx2.Text.Trim() + "."
                   + ScoreServicetbx3.Text.Trim() + "." + ScoreServicetbx4.Text.Trim() + ":" + ScoreServicePorttbx.Text.Trim() + "/ScoreService";
                AppConfigSave.SetEndpointAddress("ScoreService", ScoreService);
                //保存服务
                string DriverClient = "http://" + DriverClienttbx1.Text.Trim() + "." + DriverClienttbx2.Text.Trim() + "."
                   + DriverClienttbx3.Text.Trim() + "." + DriverClienttbx4.Text.Trim() + ":" + DriverClientPorttbx.Text.Trim() + "/DriverClientService";
                AppConfigSave.SetEndpointAddress("DriverClientService", DriverClient);
                //保存服务
                string DriverManage = "http://" + DriverManagetbx1.Text.Trim() + "." + DriverManagetbx2.Text.Trim() + "."
                  + DriverManagetbx3.Text.Trim() + "." + DriverManagetbx4.Text.Trim() + ":" + DriverManagePorttbx.Text.Trim() + "/DriverManageService";
                AppConfigSave.SetEndpointAddress("DriverManageService", DriverManage);
                //保存服务
                string AccountManage = "http://" + AccountManagetbx1.Text.Trim() + "." + AccountManagetbx2.Text.Trim() + "."
                  + AccountManagetbx3.Text.Trim() + "." + AccountManagetbx4.Text.Trim() + ":" + AccountManagePorttbx.Text.Trim() + "/AccountManageService";
                AppConfigSave.SetEndpointAddress("AccountManageService", AccountManage);
                //保存服务
                string Database = "http://" + Databasetbx1.Text.Trim() + "." + Databasetbx2.Text.Trim() + "."
                  + Databasetbx3.Text.Trim() + "." + Databasetbx4.Text.Trim() + ":" + DatabasePorttbx.Text.Trim() + "/DatabaseService";
                AppConfigSave.SetEndpointAddress("DatabaseService", Database);
                //保存服务
                string DispatcherManage = "http://" + DispatcherManagetbx1.Text.Trim() + "." + DispatcherManagetbx2.Text.Trim() + "."
                  + DispatcherManagetbx3.Text.Trim() + "." + DispatcherManagetbx4.Text.Trim() + ":" + DispatcherManagePorttbx.Text.Trim() + "/DispatcherManageService";
                AppConfigSave.SetEndpointAddress("DispatcherManageService", DispatcherManage);
                //保存服务
                string DispatcherClient = "http://" + DispatcherClienttbx1.Text.Trim() + "." + DispatcherClienttbx2.Text.Trim() + "."
                  + DispatcherClienttbx3.Text.Trim() + "." + DispatcherClienttbx4.Text.Trim() + ":" + DispatcherClientPorttbx.Text.Trim() + "/DispatcherClientService";
                AppConfigSave.SetEndpointAddress("DispatcherClientService", DispatcherClient);
                App.Current.Shutdown();
                System.Diagnostics.Process.Start(strName);                             
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelBut_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Localtbx_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isLoaded)
            {
                TextBox textBox = sender as TextBox;
                var strMath = textBox.Text.Trim();
                int math;
                if (!int.TryParse(strMath, out math))
                {
                    MessageBox.Show("请输入正确的IP地址");
                    return;
                }
                if (math > 255 && math < 255)
                {
                    MessageBox.Show("请输入正确的IP地址");
                    return;
                }
            }
        }
    }
    public class AppConfigSave
    {
        public static void UpDataToAppKey(string key, string value)
        {
            //读取程序集的配置文件
            string assemblyConfigFile = Assembly.GetEntryAssembly().Location;

            Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyConfigFile);
            //获取appSettings节点
            AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

            //删除name，然后添加新值
            appSettings.Settings.Remove(key);
            appSettings.Settings.Add(key, value);
            //保存配置文件
            config.Save();
            // 强制重新载入配置文件的ConnectionStrings配置节
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }

        public static void AddToAppKey(string key, string value)
        {
            //读取程序集的配置文件
            string assemblyConfigFile = Assembly.GetEntryAssembly().Location;

            Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyConfigFile);
            //获取appSettings节点
            AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

            //存在不加
            if (!appSettings.Settings.AllKeys.Contains(key))
            {
                appSettings.Settings.Add(key, value);
            }
            //保存配置文件
            config.Save();
        }
        public static string GetToAppValue(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
        ///   <summary>
        ///  读取EndpointAddress
        ///   </summary>
        ///   <param name="endpointName"></param>
        ///   <returns></returns>
        public static string GetEndpointAddress(string endpointName)
        {
            ClientSection clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                if (item.Name == endpointName)
                    return item.Address.ToString();
            }
            return string.Empty;
        }
        ///   <summary>
        ///  设置EndpointAddress
        ///   </summary>
        ///   <param name="endpointName"></param>
        ///   <param name="address"></param>
        public static void SetEndpointAddress(string endpointName, string address)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                if (item.Name != endpointName)
                    continue;
                item.Address = new Uri(address);
                break;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

    }
}
